package cn.yh.register.order.api;

import cn.yh.register.common.result.Result;
import cn.yh.register.enums.PaymentTypeEnum;
import cn.yh.register.order.service.OrderService;
import cn.yh.register.order.service.PaymentInfoService;
import cn.yh.register.order.service.WeixinService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {

    @Autowired
    private WeixinService weixinService;
    @Autowired
    private PaymentInfoService paymentInfoService;


    /**
     * 下单 生成二维码
     */
    @GetMapping("/createNative/{orderId}")
    public Result<Map<String, Object>> createNative(
            @ApiParam(name = "orderId", value = "订单id", required = true)
            @PathVariable("orderId") Long orderId) {
        Map<String, Object> aNative = weixinService.createNative(orderId);
        return Result.ok(aNative);
    }

    @GetMapping("/queryPayStatus/{orderId}")
    public Result<?> queryPayStatus(@PathVariable Long orderId) {
        Map<String, String> map = weixinService.queryPayStatus(orderId, PaymentTypeEnum.WEIXIN.getComment());
        if (map == null) {
            return Result.fail();
        }
        if ("SUCCESS".equals(map.get("return_code"))
                && "SUCCESS".equals(map.get("result_code"))
                && "SUCCESS".equals(map.get("trade_state"))) {
            //支付成功 更新支付记录 & 更新订单状态  & 对接医院系统更新订单
            paymentInfoService.paySuccess(map.get("out_trade_no"),PaymentTypeEnum.WEIXIN.getStatus(), map);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }

}